<?php
	
	class Materia{
		
		public $id_materia;
		public $name;
		public $attachment = array();
		public $description;
		public $materie = null;
		
		public function __construct($id_materia=null,$name=null,$attachment=null,$description=null){
			
			$this->id_materia = $id_materia;
			$this->name = $name;
			$this->attachment = $attachment;
			$this->description = $description;
		}
		
		public function getMaterie(){
			// Preparo la query per cercare nel DB un utente con email e password corrispondenti ai dati immessi dall'utente su login
			
			$this->materie = array();
			$sql = "SELECT * FROM materia";
	
	        // Eseguo la query per tratte i risultati
	        $result = Database::getInstance()->getConnection()->Execute($sql);
	        		
	        // Se non ha trovato solo un record esce altrimenti vuoi dire che hai dati immessi corrisponde un solo utente, quindi estrapola tutti i dati di esso
			if($result->NumRows() == 0){
				return false;
			}else{
				
				while($row = $result->FetchRow()){
					$this->id_materia = $row['id_materia'];
					$this->name = $row['name'];
					$this->description = $row['description'];
					
					$sql_files = "SELECT * FROM attachment where id_materia = ?";
					$result_files = Database::getInstance()->getConnection()->Execute($sql_files, array($row['id_materia']));
	       			
					$files = array();
					if($result_files->NumRows() != 0){
						while($row_files = $result_files->FetchRow()){
							$files[] = new Attachment($row_files['id_attachment'],$row_files['name'],$row_files['date'],$row_files['description'],$row_files['id_user'],$row_files['id_materia'], $row_files['weight'], $row_files['file_url']);
						}
					}
					
					$this->materie[] = new Materia($this->id_materia, $this->name, $files, $this->description);
				}
				
				return $this->materie;
			}
		}
		
		public function getMateriaById($id_materia){
			foreach($this->materie as $materia){
				
				if($materia->id_materia == $id_materia){
					return $materia;
				}
				
			}
			
			return null;
		}
	}
?>